package com.example.demo.service;

import com.example.demo.pojo.User;
import com.example.demo.pojo.dto.UserDto;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service       // spring bean
public class UserService implements IUserService {

    @Autowired
    UserRepository userRepository;

    @Override
    public void delete(Integer userId) {
        userRepository.deleteById(userId);
    }

    @Override
    public User add(UserDto user) {
        User userPojo = new User();
//        调用数据访问类
//        Repo执行的数据库操作只能是User, 因为UserDTO可能包含其他不必要的字段.
//        所以这里先把User DTO的值复制到临时创建的userPojo,他是User类型,只会接受User需要的字段.
        BeanUtils.copyProperties(user, userPojo);
        //        这里可以返回也可以不返回, 不返回就是void, 返回就是User对象, 把Void改成User;
        return userRepository.save(userPojo);
    }

    public User edit(UserDto user) {
        User userPojo = new User();
        BeanUtils.copyProperties(user, userPojo);
        return userRepository.save(userPojo);
    }


    public User getUser(Integer userId) {
        return userRepository.findById(userId).orElseThrow(()->{
            throw new IllegalArgumentException("User not found");
        });
    }
}
